import { encryptPassword, generateRandomString, toFail, toSuccess, useEntityManager } from "@sker/core"
import { AutoUser } from "@sker/entities"
import { useData } from "@sker/runtime"
import { z } from "zod"

export default async () => {
    const input = z.object({
        mobile: z.string(),
        password: z.string()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { mobile: body.mobile } })
        if (!user) return toFail(`账号或密码错误`)
        const password = await encryptPassword(body.password, user.salt)
        if (user.password !== password) {
            return toFail(`账号或密码错误`)
        }
        if (user.is_admin !== '1') {
            return toFail(`您的账号不是代理账号`)
        }
        const token = generateRandomString(32)
        await m.update(AutoUser, user.id, { token: token })
        return toSuccess({ token, mobile: user.mobile, realname: user.realname, username: user.username, device_count: user.device_count, max_count: user.max_count, isAdmin: true })
    })
}